<%- include('header', {type: ''}) %>
<% if (!article) { %>
  <p class="tips">暂无内容</p>
<% } else { %>
  <div class="wrapper">
    <div class="card article-detail">
      <div class="card-header">
        <div class="avatar">
          <img src="/img/avatar/<%= article.avatar %>" class="avatar" alt="avatar">
        </div>
        <div class="desc">
            <span>作者：<%= article.name %></span>
            <span>评论数：<span id="comment-count"><%= commentCount %></span></span>
            <span>浏览量：<%= article.pv %></span>
            <span>发布时间：<%= article.time %></span>
        </div>
      </div>
      <div class="card-body">
        <h1 class="title"><%= article.title %></h1>
        <div class="content markdown">
          <%- article.markdown ? article.markdown : article.content %>
        </div>
      </div>
      <% if(session.user === article.name){ %>
        <div class="card-footer">
          <span class="edit" id="edit">编辑</span>
          <span class="delete" id="delete">删除</span>
        </div>
      <% }%>
    </div>
    <div class="comment-wrapper">
      <% if(!session.user){ %>
        <p class="tips">登录之后才可以评论哟~</p>
      <% } else { %>
        <form method="post" class="form form-vertical">
          <div class="form-item">
            <textarea name="content" rows="4"></textarea>
          </div>
          <div>
            <button class="btn btn-primary" id="comment">发表留言</button>
          </div>
        </form>
      <% } %>
      <% if(!comments.length){ %>
        <p class="tips">还没有评论，赶快去评论吧！</p>
      <% } else { %>
        <ul class="list comment-list">
          <% comments.forEach((item) => { %>
            <li class="list-item key-<%= item.id %>">
              <img src="/img/avatar/<%= item.avatar %>" class="avatar" alt="avatar">
              <div class="list-item-content">
                <div class="name"><%= item.name %></div>
                <div class="comment"><%= item.content %></div>
                <div class="time"><%= item.time %></div>
              </div>
              <% if(session.user === item.name ){ %>
                <span class="delete-comment" data-id="<%= item.id %>">删除</span>
              <% } %>
            </li>
          <% }) %>
        </ul>
        <a class="more" id="more">查看更多></a>
      <% } %>
    </div>
  </div>
<% } %>
<script>
$(function() {
  // 文章 id
  const articleId = window.location.pathname.split('/')[2];
  // 用户
  const user = "<%- session.user %>";

  // 发表评论
  const $comment = $('#comment')
  $comment.click((e) => {
    e.preventDefault();
    
    // 禁用按钮
    $comment.attr('disabled', true);

    const content = $('textarea').val().trim();
    if (!content) {
      $comment.removeAttr('disabled')
      return message('请输入评论!');
    }
    $.ajax({
      url: '/comment',
      type: 'POST',
      data: { content, articleId},
      dataType: 'json',
      success: (res) => {
        $comment.removeAttr('disabled')
        if  (res.code === 200) {
          message('留言发表成功');
          setTimeout(() => {
            window.location.reload();
          }, 1000)
        } else {
          return message(res.msg);
        }
      },
      error: () => {
        $comment.removeAttr('disabled')
        message('留言发表失败');
      }
    })
  })

  // 编辑文章
  $('#edit').click((e) => {
    // 跳转到文章编辑页
    window.location.href =`/edit/${articleId}`;
  })

  // 删除文章
  $('#delete').click((e) => {
    modal({
      title: '删除文章',
      content: '确定删除文章吗?',
      onOk: () => {
        $.ajax({
          url: `/delete/${articleId}`,
          type: 'DELETE',
          success: (res) => {
            if (res.code === 200) {
              message('文章删除成功');
              setTimeout(() => {
                window.location.href =`/articles?author=${user}`;
              }, 1000)
            } else {
              message(res.msg);
            }
          },
          error: () => {
            message('服务器异常');
          }
        })
      }
    })
  })

  
  // 删除评论
  const $commentList = $('.comment-list')
  let commentCount = '<%= commentCount %>'
  $commentList.on('click', '.delete-comment', function (e) {
    const id = $(this).data('id')
    $.ajax({
      url: `/comment/${id}`,
      type: 'DELETE',
      success: (res) => {
        if (res.code === 200) {
          message('评论删除成功');
          setTimeout(() => {
            // 修改评论数
            $('#comment-count').html(Number(commentCount) - 1);
            // 移除本条评论
            $('.list-item').remove(`.key-${id}`);
          }, 1000)
        } else {
          message(res.msg);
        }
      },
      error: () => {
        message('服务器异常');
      }
    })
  })

  // 查看更多评论
  let commentSize = '<%= commentSize %>'
  let commentPage = '<%= commentPage %>'
  // 判断是否显示 “查看更多” 按钮
  if (commentPage * commentSize < commentCount) {
    $('#more').show()
  }

  $('#more').click((e) => {
    let html = ''
    // 加载下一页
    commentPage = Number(commentPage) + 1

    $.ajax({
      url: `/comments?aid=${articleId}&page=${commentPage}`,
      type: 'GET',
      success: (res) => {
        if (res.code === 200) {
          const { comments, commentPage, commentSize } = res.data;
          comments.forEach(item => {
            html += `
            <li class="list-item key-${item.id}">
              <img src="/img/avatar/${item.avatar}" class="avatar" alt="avatar">
              <div class="list-item-content">
                <div class="name">${item.name}</div>
                <div class="comment">${item.content}</div>
                <div class="time">${item.time}</div>
              </div>
              ${ user === item.name ? `<span class="delete-comment" data-id="${item.id}">删除</span>` : ''} 
            </li>
            `
          })
          $commentList.append(html);
          // 判断是否显示 “查看更多” 按钮
          if (commentPage * commentSize > commentCount) {
            $('#more').hide()
          }
        } else {
          message(res.msg);
        }
      },
      error: () => {
        message('服务器异常');
      }
    })
  })

})
</script>
<% include('footer') %>